package com.wkh.datastructure.stack;

import java.util.Iterator;
//基于单向链表的栈的实现
public class LinkedListStack<E> implements Stack<E>,Iterable<E>{
    static class Node<E>{
        Node<E> next;
        E value;

        public Node(Node<E> next, E value) {
            this.next = next;
            this.value = value;
        }
    }

    private int capacity;
    private int size;
    private Node<E> head = new Node<>(null,null);

    public LinkedListStack(int capacity) {
        this.capacity = capacity;
    }

    /**
     * 像栈顶压入元素
     *
     * @param value :待压入值
     * @return true表示压入成功，false表示压入失败
     */
    @Override
    public boolean push(E value) {
        if (isFull()){
            return false;
        }
        Node<E> newNode = new Node<>(head.next, value);
        head.next = newNode;
        size++;
        return true;
    }

    /**
     * 从栈顶弹出元素
     *
     * @return 栈非空返回栈顶元素，栈为空返回null
     */
    @Override
    public E pop() {
        if (isEmpty()){
            return null;
        }
        Node<E> poped = head.next;
        head.next = poped.next;
        size--;
        return poped.value;
    }

    /**
     * 返回栈顶元素，不弹出
     *
     * @return
     */
    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        Node<E> poped = head.next;
        return poped.value;
    }

    /**
     * 判断栈是否为空
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 判断栈是否是满的
     *
     * @return
     */
    @Override
    public boolean isFull() {
        return size == capacity;
    }

    /**
     * Returns an iterator over elements of type {@code T}.
     *
     * @return an Iterator.
     */
    @Override
    public Iterator<E> iterator() {

        return new Iterator<E>() {
            Node<E> p = head.next;
            @Override
            public boolean hasNext() {
                return p != null;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }
}
